<?php
namespace App\Imports;
use App\Models\V1\Admins;
use App\Models\V1\Users;
use Illuminate\Support\Facades\Log;
use Maatwebsite\Excel\Concerns\ToModel;
class YourDataImport implements ToModel
{
    protected $user_data;
    public function __construct($user_data)
    {
        $this->user_data = $user_data;
    }
    // 用于标记是否处理第一行
    private $isFirstRow = true;
    /**
     * @param array $row
     *
     * @return \Illuminate\Database\Eloquent\Model|null
     */
    public function model(array $row)
    {


        if ($this->isFirstRow) {
            $this->isFirstRow = false;
            return null;
        }

        // 检查是否有足够的数据列
        if (count($row) < 9) {
            // 记录问题或跳过不完整的行
            Log::warning('Incomplete row detected: ' . json_encode($row));
            return null;
        }

        // 检查电话号码是否已存在
        $existingUser = Users::where('mobile', $row[2])->first();
        if ($existingUser) {
            throw new \Exception('电话重复: ' . $row[2]);
        }

        return new Users([
            'community_id' => $this->user_data['community_id'],
            'preparatory_id' => $this->user_data['id'],
            'username' => $row[1],
            'real_name' => $row[1],
            'mobile' => $row[2],
            'partition' => $row[3],
            'element' => $row[4],
            'building' => $row[5],
            'floor' => $row[6],
            'hnum' => $row[7],
            'area' => $row[8],
            'remark' => $row[9],
        ]);
    }
}
